import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';
import '../services/auth_service.dart';

class AuthProvider with ChangeNotifier {
  final AuthService _authService = AuthService();
  User? _user;
  bool _isLoading = false;
  String? _error;

  User? get user => _user;
  bool get isLoading => _isLoading;
  String? get error => _error;
  bool get isAuthenticated => _user != null;

  // 初始化 - 从本地存储加载用户信息
  Future<void> initAuth() async {
    final prefs = await SharedPreferences.getInstance();
    final userData = prefs.getString('userData');
    
    if (userData != null) {
      try {
        final userMap = jsonDecode(userData) as Map<String, dynamic>;
        _user = User.fromJson(userMap);
        
        // 验证token是否有效
        final isValid = await _authService.validateToken(_user!.token);
        if (!isValid) {
          _user = null;
          await prefs.remove('userData');
        }
      } catch (e) {
        _user = null;
        await prefs.remove('userData');
      }
    }
    
    notifyListeners();
  }

  // 用户登录
  Future<bool> login(String username, String password) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      _user = await _authService.login(username, password);
      
      // 保存用户信息到本地存储
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('userData', jsonEncode(_user!.toJson()));
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
      return false;
    }
  }

  // 用户注册
  Future<bool> register(String username, String email, String password) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      _user = await _authService.register(username, email, password);
      
      // 保存用户信息到本地存储
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('userData', jsonEncode(_user!.toJson()));
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
      return false;
    }
  }

  // 用户登出
  Future<void> logout() async {
    _user = null;
    
    // 清除本地存储的用户信息
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('userData');
    
    notifyListeners();
  }

  // 更新用户信息
  Future<bool> updateProfile(Map<String, dynamic> data) async {
    if (_user == null) {
      _error = '用户未登录';
      notifyListeners();
      return false;
    }

    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      final updatedUser = await _authService.updateProfile(_user!.token, data);
      _user = updatedUser;
      
      // 更新本地存储的用户信息
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('userData', jsonEncode(_user!.toJson()));
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
      return false;
    }
  }

  // 修改密码
  Future<bool> changePassword(String currentPassword, String newPassword) async {
    if (_user == null) {
      _error = '用户未登录';
      notifyListeners();
      return false;
    }

    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      await _authService.changePassword(_user!.token, currentPassword, newPassword);
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
      return false;
    }
  }

  // 清除错误信息
  void clearError() {
    _error = null;
    notifyListeners();
  }
}